package org.jetnuke.modules.pictures;

import java.io.File;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.jforum.util.preferences.ConfigKeys;
import net.jforum.util.preferences.SystemGlobals;

import org.apache.velocity.VelocityContext;
import org.jetnuke.common.ActionForward;
import org.jetnuke.common.IAction;
import org.jetnuke.common.IAdminInfo;
import org.jetnuke.common.IModuleInfo;
import org.jetnuke.common.IUserInfo;
import org.jetnuke.dao.DataAccessDriver;
import org.jetnuke.dao.PictureAlbumDAO;
import org.jetnuke.dao.PictureCommentDAO;
import org.jetnuke.dao.PictureDAO;
import org.jetnuke.dao.PictureVoteDAO;
import org.jetnuke.entities.Picture;
import org.jetnuke.entities.PictureAlbum;
import org.jetnuke.modules.pictures.utils.PictureUtils;
import org.jetnuke.util.JetUtil;


public class RemovePicture implements IAction {
	int pid;
	String ok;
	public void setOk(String ok) {
		this.ok = ok;
	}
	public ActionForward exec(HttpServletRequest request,
			HttpServletResponse response, VelocityContext vc, IModuleInfo info,
			String op, IUserInfo ui, IAdminInfo ai) throws Exception {
		if(ui==null || ui.getID()<2)
			return null;
		if(ok==null){
			PictureUtils.manageStyleAndBlocks(vc, ui.getID());
			vc.put("myPictures",Boolean.TRUE);
			return new ActionForward(op,info);
		}
		PictureDAO pd=DataAccessDriver.getInst().newPictureDAO();
		Picture picture=pd.retrieveByPK(pid);
		
		if(picture.getUID()!=ui.getID() )
			return null;
		String initPath=SystemGlobals.getValue(ConfigKeys.ATTACHMENTS_STORE_DIR) + "/pictures/"+ui.getID()+"/";
		File f = null;
		File pathDir=new File(initPath);
		f=new File(pathDir,picture.getFILENAME());
		if(f.exists())
			f.delete();
		if(picture.getMEDIUMNAME()!=null){
			f=new File(pathDir,picture.getMEDIUMNAME());
			if(f.exists())
				f.delete();
		}
		if(picture.getTHUMBNAME()!=null){
			f=new File(pathDir,picture.getTHUMBNAME());
			if(f.exists())
				f.delete();
		}
		int albumID=picture.getAID();
		PictureAlbumDAO pad=DataAccessDriver.getInst().newPictureAlbumDAO();
		PictureAlbum album=pad.retrieveByPK(albumID);
		if(album.getTHUMBNAIL()==picture.getPID()){
			album.setTHUMBNAIL(0);
			pad.update(album);
		}
		
		PictureCommentDAO pcd=DataAccessDriver.getInst().newPictureCommentDAO();
		pcd.deleteByPID(picture.getPID());
		PictureVoteDAO pvd=DataAccessDriver.getInst().newPictureVoteDAO();
		pvd.deleteByPID(picture.getPID());
		pd.deleteByPID(picture.getPID());
		JetUtil.redirect(vc,response,request.getContextPath()+"/do/pictures/show_album?aid="+albumID);
		return null;
	}
	public void setPid(int pid) {
		this.pid = pid;
	}

}
